package org.smart4j.chapter1.util;


import org.smart4j.chapter1.annotation.Inject;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @ClassName:
 * @Description: BeanHelper获取所有BeanMap，然后遍历这个映射关系，
 * 进而通过反射获取类中的所有成员变量。然后遍历这些成员变量是否带有Inject注解，
 * 若带有该注解，则从BeanMap中根据Bean类取出Bean实例，
 * 最后通过ReflectionUtil#setField方法来修改当前成员变量的值
 * @Author: LynnZou
 * @Date: 2017/5/27
 */
public final class IocHelper {

    static {

        Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
        if (CollectionUtil.isNotEmpty(beanMap)) {
            //遍历Bean Map
            for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) {
                //从BeanMap中获取Bean类与Bean实例
                Class<?> beanClass = beanEntry.getKey();
                Object beanInstance = beanEntry.getValue();
                //获取Bean类定义的所有成员变量（简称 Bean Field）
                Field[] beanFields = beanClass.getDeclaredFields();
                if (ArrayUtil.isNotEmpty(beanFields)) {
                    //遍历Bean Field
                    for (Field beanField : beanFields) {
                        //判断当前Bean Field是否带有Inject注解
                        if (beanField.isAnnotationPresent(Inject.class)) {
                            //在Bean Map中获取Bean Field对应的实例
                            Class<?> beanFieldClass = beanField.getType();
                            Object beanFieldInstance = beanMap.get(beanFieldClass);
                            if (beanFieldInstance != null) {
                                //通过反射初始化BeanField的值
                                ReflectionUtil.setField(beanInstance, beanField, beanFieldInstance);
                            }
                        }
                    }
                }
            }
        }
    }

}
